package controller;

import com.google.gson.Gson;
import entity.*;
import http_post.src.Sendsms;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.NameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import relationEntity.CollectionProduct;
import relationEntity.OrderProduct;
import relationEntity.ProductsDetails;
import service.*;
import util.CreateOrder;
import util.Page;
import weixinpay.WeiXinPay;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.slf4j.MDC.get;
import static weixinpay.WeiXinPay.WX_PARTNER_ID;

/**
 * Created by jifeng on 2016/12/30 0030.微信移动端商城
 */
@Controller
public class MobileTerminalController {

    @Resource(name = "productService")
    private ProductService productService;
    @Resource(name = "userService")
    private UserService service;
    @Resource(name = "orderService")
    private OrderService orderService;


    /** 商户平台和开发平台约定的API密钥，在商户平台设置 */
    public static final String key="ZC6EGWXA2DXO2OYWWAWKKWQ729GLSYXE";
    /** APP_ID 应用从官方网站申请到的合法appId */
    public static final String WX_APP_ID = "wx079bba8222507669";
    /**
     * Created by jifeng
     * 移动端商城首页
     * */
    @RequestMapping(value = "/frontEndIndex")
    public Model frontEndIndex(HttpServletRequest request, HttpServletResponse response,Model mv){
        try {
        String pageNo = request.getParameter("pageNo");
        if (pageNo == null) {
            pageNo = "1";
        }
            String code =request.getParameter("code");
            //String state = request.getParameter("state");
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxcfff48663c212c9d&secret=05b4a4fc61e7450e88941abbf3bf74c3&code="+code+"&grant_type=authorization_code";
            String json = loadJson(url);
            Gson gs = new  Gson();
            Map<String,String> map = gs.fromJson(json, Map.class);
            String openid =map.get("openid");
           // String access_token =map.get("access_token");
            System.out.print(json+"----"+"111111");
            //可以获取到微信用户的个人资料,此处为了方便只取了唯一标识openId,在库中插入一条user信息
           /* String urls="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"";
            String jsons = loadJson(urls);
            System.out.print(jsons+"----"+"111111");*/
            if (openid!=null){
                List<User> userList = service.findUserByPhone(openid);
                if (userList.size()==0) {
                    long time = System.currentTimeMillis();
                    String head = "kaa";
                    User user = new User();
                    String userName = head + time;
                    String token = time + openid;
                    user.setUserName(userName);
                    user.setToken(token);
                    user.setOrderNum(0);
                    user.setDeletes(0);
                    user.setSource("wap");
                    user.setOpenId(openid);
                    user.setPhone(openid);
                    service.addUser(user);
                }
                request.getSession().setAttribute("phone",openid);
            }
            /*String phone = request.getParameter("phone");
            request.getSession().setAttribute("phone",phone);*/
        /*String phone = request.getParameter("phone");*/
        request.getSession().getAttribute("phone");
        /*System.out.print(phone+"2222"+11);*/
        String name = request.getParameter("productName");
            String productName = null;
        if (name!=null){
             productName = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        }
        int pageSize =4*Integer.valueOf(pageNo);
        Page page =productService.frontEndProductList(1,productName,pageSize);
        mv.addAttribute("page",page);
        List<Product> productList = page.getList();
        List<Advertisement> advertisementList =service.findAdvertisementList();
        mv.addAttribute("productName",productName);
        if (name==null || name=="") {
            mv.addAttribute("advertisementList", advertisementList);
        }
        mv.addAttribute("productList",productList);
        mv.addAttribute("type",productList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    public static String loadJson (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    /**
     * Created by jifeng
     * 移动端商品详情
     * */
    @RequestMapping(value = "/productDetails")
    public Model productDetails(HttpServletRequest request,HttpServletResponse response,Model mv){

        try {
            String phone = String.valueOf(request.getSession().getAttribute("phone"));
            String pageNo = request.getParameter("pageNo");
            String id = request.getParameter("productId");
            List<Collection> collectionList =null;
            if (pageNo == null) {
                pageNo = "1";
            }
            if (phone!=null && phone!="null") {
                User user = service.findUserByPhone(phone).get(0);
                collectionList = productService.findByProductIdAndUserId(Integer.valueOf(id), user.getId());
                mv.addAttribute("type",collectionList.size());
            }else {
                mv.addAttribute("type",0);
            }
            Page page =productService.commetList(Integer.valueOf(pageNo),Integer.valueOf(id),4);
            mv.addAttribute("page",page);
            List<Comment> commentList = page.getList();
            mv.addAttribute("commentList",commentList);
            mv.addAttribute("commentListSize",commentList.size());
            if (collectionList !=null && collectionList.size()!=0){
                mv.addAttribute("collection",collectionList.get(0));
            }
            List<ProductsDetails> productsDetailsList = productService.displayProductDetails(Integer.valueOf(id));
            mv.addAttribute("ProductsDetails", productsDetailsList.get(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * Created by jifeng
     * 收藏商品
     * */
    @RequestMapping(value = "/addCollection")
    public String addCollection(HttpServletRequest request,HttpServletResponse response){
        String phone = String.valueOf(request.getSession().getAttribute("phone"));
        if (phone!=null&&phone!="null") {
            String id = request.getParameter("id");
            User user = service.findUserByPhone(phone).get(0);
            Collection collection = new Collection();
            collection.setProductId(Integer.valueOf(id));
            collection.setUserId(user.getId());
            productService.addCollection(collection);
            return "redirect:/productDetails?productId=" + id + "";
        }else {
            return "redirect:/login";
        }
    }

    /**
     * Created by jifeng
     * 取消收藏商品
     * */
    @RequestMapping(value = "/deleteCollection")
    public String deleteCollection(HttpServletRequest request,HttpServletResponse response){
        String collectionId= request.getParameter("collectionId");
        String id = request.getParameter("id");
        productService.deleteCollection(Integer.valueOf(collectionId));
        return "redirect:/productDetails?productId="+id+"";
    }

    /**
     * Created by jifeng
     * 跳转到创建订单页面
     * */
    @RequestMapping(value = "/orderConfirm")
    public ModelAndView orderConfirm(HttpServletRequest request,HttpServletResponse response){
        String phone = String.valueOf(request.getSession().getAttribute("phone"));
        ModelAndView mv = new ModelAndView();
        if (phone!=null && phone!="null") {
            User user = service.findUserByPhone(phone).get(0);
            String productId = request.getParameter("productId");
            String num = request.getParameter("num");
            String addressId = request.getParameter("addressId");
            if (addressId != null) {
                Address address = orderService.findUserAddress(Integer.valueOf(addressId));
                mv.addObject("address", address);
                mv.addObject("type", 1);
            } else {
                if (user.getAddressId() != 0) {
                    Address address = orderService.findUserAddress(user.getAddressId());
                    mv.addObject("address", address);
                    mv.addObject("type", 1);
                } else {
                    List<Address> addressList = orderService.findUserAddressByUserId(user.getId());
                    if (addressList.size() != 0) {
                        mv.addObject("address", addressList.get(0));
                        mv.addObject("type", 1);
                    } else {
                        mv.addObject("type", 0);
                    }
                }
            }
            Product product = productService.findProductById(Integer.valueOf(productId));
            long totalMoney = product.getNowPrice() * Long.valueOf(num);
            mv.addObject("product", product);
            mv.addObject("num", num);
            mv.addObject("totalMoney", totalMoney);
            mv.addObject("userId", user.getId());
            return mv;
        }else {
            mv.setViewName("login");
            return mv;
        }
    }


    /**
     * Created by jifeng
     * 跳转到收货地址列表
     * */
    @RequestMapping(value = "/addSelect")
    public Model addSelect(HttpServletRequest request,HttpServletResponse response,Model mv){
        try {
            String pageNo = request.getParameter("pageNo");
            if (pageNo == null) {
                pageNo = "1";
            }
        String userId=request.getParameter("userId");
        String productId = request.getParameter("productId");
        String num = request.getParameter("num");
        String addressSelect = request.getParameter("adSelect");
        if (addressSelect!=null){
            service.updateDefault(Integer.valueOf(userId),Integer.valueOf(addressSelect));
        }
            int pageSize =50*Integer.valueOf(pageNo);
            Page page =orderService.findUserAddressByUserId(1,Integer.valueOf(userId),pageSize);
            mv.addAttribute("page",page);
            List<Address> addressList = page.getList();
        User user = service.findUserById(Integer.valueOf(userId));
        mv.addAttribute("productId",productId);
        mv.addAttribute("num",num);
        mv.addAttribute("userId",userId);
        mv.addAttribute("addressId",user.getAddressId());
        mv.addAttribute("userAddressList",addressList);
        } catch (Exception e) {
        e.printStackTrace();
    }
        return mv;
    }

    /**
     * Created by jifeng
     * 选择收货跳转到创建订单
     * */
    @RequestMapping(value = "/toOrderConfirm")
    public String toOrderConfirm(HttpServletRequest request,HttpServletResponse response){
        String productId = request.getParameter("productId");
        String num = request.getParameter("num");
        String id=request.getParameter("addSelect");
        return "redirect:/orderConfirm?addressId="+id+"&productId="+productId+"&num="+num+"";
    }


    /**
     * Created by jifeng
     * 跳到创建收货地址
     * */
    @RequestMapping(value = "/newAddress")
    public Model newAddress(HttpServletRequest request,HttpServletResponse response,Model mv){
        String userId=request.getParameter("userId");
        String productId = request.getParameter("productId");
        String num = request.getParameter("num");
        mv.addAttribute("productId",productId);
        mv.addAttribute("num",num);
        mv.addAttribute("userId",userId);
        return mv;
    }

    /**
     * Created by jifeng
     * 创建收货地址
     * */
    @RequestMapping(value = "/addAddress")
    public String addAddress(HttpServletRequest request,HttpServletResponse response){
        String userId=request.getParameter("userId");
        String productId = request.getParameter("productId");
        String num = request.getParameter("num");
        String addressee =request.getParameter("addressee");
        String addressPhone =request.getParameter("addressPhone");
        String zipCode =request.getParameter("zipCode");
        String detailed =request.getParameter("detailed");
        Address address = new Address();
        address.setDetailed(detailed);
        address.setUserId(Integer.valueOf(userId));
        address.setAddressee(addressee);
        address.setAddressPhone(addressPhone);
        address.setZipCode(zipCode);
        orderService.addAddress(address);
        return "redirect:/addSelect?num="+num+"&userId="+userId+"&productId="+productId+"";
    }

    /**
     * Created by jifeng
     * 创建订单
     * */
    @RequestMapping(value = "/orderPay")
    public Model orderPay(HttpServletRequest request,HttpServletResponse response,Model mv){
        String userId = request.getParameter("userId");
        String productId=request.getParameter("productId");
        String addressId=request.getParameter("addressId");
        String num= request.getParameter("num");
        String totalMoney=request.getParameter("totalMoney");
        String invoice=request.getParameter("invoice");
        String invoiceType=request.getParameter("invoiceType");
        String invoiceRise=request.getParameter("invoiceRise");
        Orders orders = new Orders();
        orders.setPaymentStatus("未付款");
        orders.setToExamineStatus("未审核");
        orders.setSendStatus("未发货");
        orders.setOrderType("微信订单");
        orders.setPaymentType("微信支付");
        if (invoice!=null){
            orders.setInvoice(1);
        }else {
            orders.setInvoice(0);
        }
        orders.setTotalMoney(Long.valueOf(totalMoney));
        orders.setNum(Integer.valueOf(num));
        orders.setProductId(Integer.valueOf(productId));
        orders.setUserId(Integer.valueOf(userId));
        orders.setAddress(Integer.valueOf(addressId));
        orders.setInvoiceType(invoiceType);
        orders.setInvoiceRise(invoiceRise);
        orders.setDeletes(0);
        orderService.addOrder(orders);
        String orderCode=CreateOrder.formateCode(Integer.valueOf(userId),orders.getId());
        orderService.updateOrder(orderCode,orders.getId());
        /*Orders orders1 = orderService.findOrderById(orders.getId());*/
        Address address = orderService.findUserAddress(Integer.valueOf(addressId));
        mv.addAttribute("orders",orderCode);
        mv.addAttribute("address",address);
        mv.addAttribute("totalMoney",totalMoney);
        return mv;
    }

    /**
     * Created by jifeng
     * 个人中心
     * */
    @RequestMapping(value = "/personal")
    public ModelAndView personal(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView();
        String phone = String.valueOf(request.getSession().getAttribute("phone"));
        if (phone!=null&& phone!="null") {
            User user = service.findUserByPhone(phone).get(0);
            mv.addObject("user", user);
            return mv;
        }else {
            mv.setViewName("login");
            return mv;
        }
    }

    /**
     * Created by jifeng
     * 订单列表
     * */
    @RequestMapping(value = "/orderLists")
    public Model orderLists(HttpServletRequest request,HttpServletResponse response,Model mv){
        String userId= request.getParameter("userId");
        List<OrderProduct> orderProductList = orderService.findOrdersListByUserId(Integer.valueOf(userId));
        mv.addAttribute("orderProductList",orderProductList);
        mv.addAttribute("size",orderProductList.size());
        return mv;
    }

    /**
     * Created by jifeng
     * 收藏列表
     * */
    @RequestMapping(value = "/myCollection")
    public Model myCollection(HttpServletRequest request,HttpServletResponse response,Model mv){
        String userId= request.getParameter("userId");
        List<CollectionProduct> collectionProductList = orderService.findCollection(Integer.valueOf(userId));
        mv.addAttribute("collectionProductList",collectionProductList);
        mv.addAttribute("size",collectionProductList.size());
        return mv;
    }

    /**
     * Created by jifeng
     * 收货地址列表(以及设置默认地址)
     * */
    @RequestMapping(value = "/addressList")
    public Model addressList(HttpServletRequest request,HttpServletResponse response,Model mv){
        try {
            String pageNo = request.getParameter("pageNo");
            if (pageNo == null) {
                pageNo = "1";
            }
        String userId= request.getParameter("userId");
        String addressSelect = request.getParameter("adSelect");
        if (addressSelect!=null){
            service.updateDefault(Integer.valueOf(userId),Integer.valueOf(addressSelect));
        }
            int pageSize =50*Integer.valueOf(pageNo);
            Page page =orderService.findUserAddressByUserId(1,Integer.valueOf(userId),pageSize);
            mv.addAttribute("page",page);
        List<Address> addressList = page.getList();
        User user = service.findUserById(Integer.valueOf(userId));
        mv.addAttribute("userId",userId);
        mv.addAttribute("addressId",user.getAddressId());
        mv.addAttribute("addressList",addressList);
        mv.addAttribute("size",addressList.size());
        } catch (Exception e) {
        e.printStackTrace();
     }
        return mv;
    }

    /**
     * Created by jifeng
     * 跳转添加地址(个人中心)
     * */
    @RequestMapping(value = "/toSaveAddress")
    public Model toSaveAddress(HttpServletRequest request,HttpServletResponse response,Model mv){
        String userId= request.getParameter("userId");
        mv.addAttribute("userId",userId);
        return mv;
    }

    /**
     * Created by jifeng
     * 添加地址(个人中心)
     * */
    @RequestMapping(value = "/SaveAddress")
    public String SaveAddress(HttpServletRequest request,HttpServletResponse response){
        String userId= request.getParameter("userId");
        String addressee =request.getParameter("addressee");
        String addressPhone =request.getParameter("addressPhone");
        String zipCode =request.getParameter("zipCode");
        String detailed =request.getParameter("detailed");
        Address address = new Address();
        address.setDetailed(detailed);
        address.setUserId(Integer.valueOf(userId));
        address.setAddressee(addressee);
        address.setAddressPhone(addressPhone);
        address.setZipCode(zipCode);
        orderService.addAddress(address);
        return "redirect:/addressList?userId="+userId+"";
    }

    /**
     * Created by jifeng
     * 前端登录界面
     * */
    @RequestMapping(value = "/login")
    public Model login(HttpServletRequest request ,HttpServletResponse response,Model mv){
        String resps = String.valueOf(request.getSession().getAttribute("resp"));
        String resp=null;
        if (resps!=null) {
            if (resps.equals("3")) {
                resp = "账号或者密码错误!";
            }
        }
        mv.addAttribute("resp",resp);
        request.getSession().removeAttribute("resp");
        return mv;
    }

    /**
     * Created by jifeng
     * 前端注册界面
     * */
    @RequestMapping(value = "/register")
    public Model register(HttpServletRequest request,HttpServletResponse response,Model mv){
        String phone = String.valueOf(request.getSession().getAttribute("phone"));
        String password = String.valueOf(request.getSession().getAttribute("password"));
        String resps = String.valueOf(request.getSession().getAttribute("resp"));
        String resp=null;
        if (resps!=null){
            if (resps.equals("1")){
             resp="对不起号码已存在!";
         }
            if (resps.equals("2")){
             resp="验证码错误!";
         }
        }
        mv.addAttribute("resp",resp);
        mv.addAttribute("phone",phone);
        mv.addAttribute("password",password);
        return mv;
    }


    /**
     * Created by jifeng
     * 获取验证码
     * */
    @RequestMapping(value = "/captcha_send")
    public String captcha_send(HttpServletRequest request,HttpServletResponse response){
        String phone=request.getParameter("phone");
        Sendsms.captcha(phone,request);
         String mobile_code= String.valueOf(request.getSession().getAttribute("mobile_code"));
         System.out.print(mobile_code);
        return "redirect:/register";
    }

    /**
     * Created by jifeng
     * 注册
     * */
    @RequestMapping(value = "/saveRegister")
    public String saveRegister(HttpServletRequest request,HttpServletResponse response){
        long time = System.currentTimeMillis();
        String head ="kaa";
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        String yzm = request.getParameter("yzm");
        String captcha =String.valueOf(request.getSession().getAttribute("mobile_code"));
        request.getSession().setAttribute("phone",phone);
        request.getSession().setAttribute("password",password);
        List<User> userList = service.findUserByPhone(phone);
        if (yzm.equals(captcha)){
            if (userList.size()==0){
            User user = new User();
            String userName = head + time;
            String token = time + phone;
            user.setPhone(phone);
            user.setUserName(userName);
            user.setToken(token);
            user.setOrderNum(0);
            user.setDeletes(0);
            user.setSource("wap");
            user.setPassword(password);
            service.addUser(user);
           /* request.getSession().removeAttribute("phone");*/
            request.getSession().removeAttribute("password");
            request.getSession().removeAttribute("resp");
            return "redirect:/frontEndIndex";
        }else {
            int resp=1;
            request.getSession().setAttribute("resp",resp);
            return "redirect:/register";
        }
        }else {
            int resp=2;
            request.getSession().setAttribute("resp",resp);
            return "redirect:/register";
        }

    }


    /**
     * Created by jifeng
     * 前端商城登录
     * */
    @RequestMapping(value = "/toLogin")
    public String toLogin(HttpServletRequest request,HttpServletResponse response) {
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        List<User> userList = service.findUserByPhonePd(phone, password);
        if (userList.size() == 0) {
            int resp=3;
            request.getSession().setAttribute("resp",resp);
            return "redirect:/login";
        } else {
            request.getSession().setAttribute("phone", phone);
            return "redirect:/frontEndIndex";
        }
    }


    /**
     * Created by jifeng
     * 前端商城退出登录
     * */
    @RequestMapping(value = "/signOut")
    public String signOut(HttpServletRequest request,HttpServletResponse response){
        request.getSession().removeAttribute("phone");
        return "redirect:/login";
    }

    /**
     * Created by jifeng
     * 跳转修改收货地址
     * */
    @RequestMapping(value = "/editAddress")
    public Model editAddress(HttpServletRequest request,HttpServletResponse response,Model mv){
        String addressId=request.getParameter("addressId");
        String userId=request.getParameter("userId");
        Address address =orderService.findAddressById(Integer.valueOf(addressId));
        mv.addAttribute("address",address);
        mv.addAttribute("addressId",addressId);
        mv.addAttribute("userId",userId);
        return mv;
    }

    /**
     * Created by jifeng
     * 修改收货地址
     * */
    @RequestMapping(value = "/updateAddress")
    public String updateAddress(HttpServletRequest request,HttpServletResponse response){
        String addressId=request.getParameter("addressId");
        String userId=request.getParameter("userId");
        String addressee =request.getParameter("addressee");
        String addressPhone =request.getParameter("addressPhone");
        String zipCode =request.getParameter("zipCode");
        String detailed =request.getParameter("detailed");
        orderService.updateAddresses(Integer.valueOf(userId),Integer.valueOf(addressId),addressee,addressPhone,zipCode,detailed);
        return "redirect:/addressList?userId="+userId+"";
    }

    /**
     * Created by jifeng
     * 删除收货地址
     * */
    @RequestMapping(value = "/deleteAddresses")
    public String deleteAddresses(HttpServletRequest request,HttpServletResponse response){
        String userId=request.getParameter("userId");
        String addressId=request.getParameter("addressId");
        User user = service.findUserById(Integer.valueOf(userId));
        if (user.getAddressId() != Integer.valueOf(addressId)){
            service.deleteAddresses(Integer.valueOf(addressId));
        }else {
            service.updateUser(Integer.valueOf(userId));
            service.deleteAddresses(Integer.valueOf(addressId));
        }
        return "redirect:/addressList?userId="+userId+"";
    }


    /**
     * Created by jifeng
     * 微信支付跳转支付界面
     * */
    @RequestMapping(value = "/toWeiXinPay")
    public Model toWeiXinPay(HttpServletRequest request,HttpServletResponse response,Model mv){
        String code =request.getParameter("code");
        String orderCode = request.getParameter("orderCode");//订单号
        request.getSession().setAttribute("orderCode",orderCode);
        String price =String.valueOf(request.getSession().getAttribute("realPayPrice"));//支付金额
        System.out.print(orderCode+"-----"+price);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx079bba8222507669&secret=fa10d617075d0a950bec57977d3117ce&code="+code+"&grant_type=authorization_code";
        String json = loadJson(url);
        Gson gs = new  Gson();

        Map<String,String> map = gs.fromJson(json, Map.class);
       // System.out.print("map="+map+"-----");
        String openid =map.get("openid");
        System.out.print("openid="+openid+"-----");
        String ip ="118.178.124.242";
       WeiXinPay weiXinPay = new WeiXinPay();
        String result=get("xml");
        try {
            result = weiXinPay.submitOrder(request,Integer.valueOf(price),0,ip,openid,orderCode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(result);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = doc.getRootElement();
        Element  prepay_id = root.element("prepay_id");
        String prepay_id_text = prepay_id.getText();
        //System.out.print(prepay_id_text);
        String nonce_str = UUID.randomUUID().toString().replace("-", "");
        String packages = "prepay_id="+prepay_id_text;
        String signType="MD5";
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new NameValuePair("appId", WX_APP_ID));
        nvps.add(new NameValuePair("nonceStr",  nonce_str));
        nvps.add(new NameValuePair("package", packages));
        nvps.add(new NameValuePair("signType", signType));
        nvps.add(new NameValuePair("timeStamp",String.valueOf(System.currentTimeMillis()).toString().substring(0,10)));
        StringBuffer sb = new StringBuffer();

        for (NameValuePair nvp : nvps) {
            sb.append(nvp.getName() + "=" + nvp.getValue() + "&");
        }

        String signA = sb.toString(); // 根据签名格式组装数据，详见微信支付api
        //System.out.println(signB);
        String stringSignTemp = signA + "key=" + key; // 根据签名格式组装数据，详见微信支付api
        //System.out.println("signA=" + signA);
        System.out.println("stringSignTemp=" + stringSignTemp);
        String sign = DigestUtils.md5Hex(
                WeiXinPay.getContentBytes(stringSignTemp, "UTF-8")).toUpperCase();
        //System.out.print("SIGN="+sign);
        mv.addAttribute("prepay_id",prepay_id_text);
        mv.addAttribute("timeStamp",String.valueOf(System.currentTimeMillis()).toString().substring(0,10));
        mv.addAttribute("nonce_str",nonce_str);
        mv.addAttribute("sign",sign);
        mv.addAttribute("orderCode",orderCode);
        return mv;
    }
}
